/**   
 * @Title: RedisAPI.java 
 * @Package com.boco.traffic.redis 
 * @Description: TODO(用一句话描述该文件做什么) 
 * @author cssuger@163.com   
 * @date 2015年12月14日 下午2:31:02 
 * @version V1.0   
 */
package com.bicon.base.data.common;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bicon.base.data.common.exception.BusinessException;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;

/**
 * @ClassName: RedisAPI
 * @Description: REDIS api
 * @author cssuger@163.com
 * @date 2015年12月14日 下午2:31:02
 * 
 */
public class RedisAPI {

	private static Logger logger = LoggerFactory.getLogger(RedisAPI.class);

	private static  JedisPool pool = null;

	private static final Properties properties =  new PropertiesUtil(Constants.REDIS_PROPERTIES_PATH,false).getProperties();

	// private static final PropertiesUtil pro = new PropertiesUtil("db.properties",false);
	
	
	/**
	 * 构建redis连接池
	 * 
	 * @param ip
	 * @param port
	 * @return JedisPool
	 */
	public static JedisPool getPool() {
		if (pool == null) {
			
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMinIdle(10);
			config.setMaxTotal(Integer.parseInt(properties.getProperty("redis_maxIdle", "10")));
			// 控制一个pool可分配多少个jedis实例，通过pool.getResource()来获取；
			// 如果赋值为-1，则表示不限制；如果pool已经分配了maxActive个jedis实例，则此时pool的状态为exhausted(耗尽)。
			// config.setMaxActive(500);
			// 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。	
			config.setMaxIdle(Integer.parseInt(properties.getProperty("redis_max_total","600")));
			// 表示当borrow(引入)一个jedis实例时，最大的等待时间，如果超过等待时间，则直接抛出JedisConnectionException；
			// config.setMaxWait(1000 * 100);
			config.setMaxWaitMillis(Integer.parseInt(properties.getProperty("redis_maxWait_millis","500")));
			// 在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
			config.setTestOnBorrow(true);
			config.setTestOnReturn(true);
			pool = new JedisPool(config, properties.getProperty("redis_host","192.168.1.110"),Integer.parseInt(properties.getProperty("redis_port","6379")));
//			 pool  = new JedisPool(config, properties.getProperty("redis_host","192.168.0.92"),
//					Integer.parseInt(properties.getProperty("redis_port","6379")),0,Constants.REDIS_AUTH_PASSWORD);
		}
		return pool;
	}

	/**
	 * 返还到连接池
	 * 
	 * @param pool
	 * @param redis
	 */
	@SuppressWarnings("deprecation")
	public static void returnResource(JedisPool pool, Jedis redis) {
		if (redis != null) {
			pool.returnResource(redis);
		}
		
	}

	
	@SuppressWarnings("deprecation")
	public static void hmadd(String key, Map<String,String> map) {
		Jedis jedis = null;
		Pipeline pipeline = null;
		try {
			jedis = instance();
			if (null != jedis) {
				pipeline = jedis.pipelined();
				pipeline.sync();
				pipeline.hmset(key, map);
			}
		} catch (Exception ex) {
			pool.returnBrokenResource(jedis);
			logger.error("未知错误!", ex.getCause());
			ex.printStackTrace();
		} finally {
			returnResource(pool, jedis);
		}

	}

	/**
	 * 
	 * @Title: instance
	 * @Description: 获取实例
	 * @param @return 设定文件
	 * @return Jedis 返回类型
	 * @throws
	 */
	@SuppressWarnings("deprecation")
	protected static Jedis instance() {
		Jedis jedis = null;
		try {
			JedisPool pool = getPool();
			jedis = pool.getResource();
			return jedis;
		} catch (Exception ex) {
			logger.error("未知错误!", ex.getCause());
			pool.returnBrokenResource(jedis);
			throw new BusinessException(Constants.ERROR_STATE, Constants.ERROR_TIP);
		}
		
	}

	/**
	 * 
	 * @Title: add
	 * @Description: 一般的写入数据方法
	 * @param @param key
	 * @param @param value 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	@SuppressWarnings("deprecation")
	public static void add(String key, String value) {
		Jedis jedis = null;
		try {
			jedis = instance();
			if (null != jedis) {
				jedis.set(key, value);
			}
			if(key.length()>0&&value.length()>0){
				jedis.set(key, value);
			}
		} catch (Exception ex) {
			logger.error("未知错误!", ex.getCause());
			pool.returnBrokenResource(jedis);
			ex.printStackTrace();
		} finally {
			returnResource(pool, jedis);
		}

	}

	/**
	 * @throws IOException 
	 * 
	 * @Title: writeByMultKey
	 * @Description: 针对多级key的写入
	 * @param @param key
	 * @param @param hash 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	@SuppressWarnings("deprecation")
	public static void addBatch(Map<String,String> map,boolean isexp)  {
		Jedis jedis = null;
		Pipeline pipeline = null;
		try {
			jedis = instance();
			if (null != jedis) {
				pipeline = jedis.pipelined();
				pipeline.sync();
				if (!map.isEmpty()) {
				  for(Map.Entry<String, String> entry :map.entrySet()){
					pipeline.set(entry.getKey(), entry.getValue());
				  }
				  pipeline.sync();
				 
				}
			}
		} catch (Exception ex) {
			logger.error("未知错误!",ex.fillInStackTrace());
			pool.returnBrokenResource(jedis);
			ex.printStackTrace();
		}  finally {
			returnResource(pool, jedis);
			closeResource(pipeline);
		}

	}

	
	/**
	 * 
	 * @Title: writeByMultKey
	 * @Description: 针对多级key的写入
	 * @param @param key
	 * @param @param hash 设定文件
	 * @return void 返回类型
	 * @throws
	 */
//	public static void writeByMultKeyBatch(List<ConsumMomeyLimitVo> list) {
//		Jedis jedis = null;
//		Pipeline pipeline = null;
//		try {
//			jedis = instance();
//			if (null != jedis) {
//				pipeline = jedis.pipelined();
//				pipeline.sync();
//				if (!list.isEmpty()) {
//					
//					//int i = 0;
//					for (ConsumMomeyLimitVo vo : list) {
//						pipeline.hmset(vo.getKey(), vo.getLimtMap());
////						for(Map.Entry<String, String> entry : vo.getMap().entrySet()){
////							//logger.info("key:{},filed:{},value:{}",new String[]{vo.getKey(), entry.getKey(), entry.getValue()});
////							pipeline.hset(vo.getKey(), DealTools.mkString(entry.getKey()), DealTools.mkString(entry.getValue()));
////						}
//						//i++;
//						//pipeline.hmset(vo.getKey(), vo.getMap());
//						//logger.info(vo.getMap().toString());
//						
//						pipeline.sync();
//					}
//				}
//			}
//		} catch (Exception ex) {
//			logger.error("未知错误!",ex.fillInStackTrace());
//			pool.returnBrokenResource(jedis);
//			ex.printStackTrace();
//		}  finally {
//			returnResource(pool, jedis);
//			closeResource(pipeline)	;
//		}
//
//	}

	
	private static void closeResource(Pipeline pipeline){
		
		try {
			if (null != pipeline) {
				pipeline.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
	}
	



	/**
	 * 
	 * @Title: keyexit
	 * @Description: 判断key是否存在
	 * @param @param key
	 * @param @return 设定文件
	 * @return boolean 返回类型
	 * @throws
	 */
	@SuppressWarnings("deprecation")
	public  static int  keyexit(String key) {
		Jedis jedis = null;
		try {
			jedis = instance();
			if (null != jedis) {
				boolean flage = jedis.exists(key);
				 return flage ?1 : 2;
			}

		} catch (Exception ex) {
			pool.returnBrokenResource(jedis);
			logger.error("未知错误!", ex.getCause());
			ex.printStackTrace();
			return -1;
		} finally {
			returnResource(pool, jedis);
		}
		return 0;
		

	}
	/**
	 * 
	 * @Title: flushAllData
	 * @Description: 清除所有数据
	 * @param 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	@SuppressWarnings("deprecation")
	public static void flushAllData() {
		Jedis jedis = null;
		try {
			jedis = instance();
			if (null != jedis) {
				jedis.flushAll();
			}
		} catch (Exception ex) {
			pool.returnBrokenResource(jedis);
			logger.error("未知错误!", ex.getCause());
			ex.printStackTrace();
		} finally {
			returnResource(pool, jedis);
			
		}
	}

	
	/**
	 * 
	 * @Title: scanAllKey
	 * @Description: scanAllKey
	 * @param @param keyPrarm
	 * @param @return 设定文件
	 * @return Map<String,String> 返回类型
	 * @throws
	 */
	@SuppressWarnings("deprecation")
	public static Set<String> scanAllKey(String keyPrarm) {
		Jedis jedis = null;
		Pipeline pipeline = null;
		try {
			jedis = instance();
			pipeline = jedis.pipelined();
			if (null != jedis) {
				// 获取当前所有的key
				Response<Set<String>> response = pipeline.keys(keyPrarm);
				pipeline.sync();
				// 进行变量
				Set<String> set = response.get();
				return set;
			}
		} catch (Exception ex) {
			pool.returnBrokenResource(jedis);
			logger.error("未知错误!", ex.getCause());
			ex.printStackTrace();
		} finally {
			returnResource(pool, jedis);
			closeResource(pipeline);
		}
		return null;
	}
	
	public static Map<String, String> scanByHKey(String key) {
		Jedis jedis = null;
		try {
			jedis = instance();
			if (null != jedis) {
				Map<String, String> map = jedis.hgetAll(key);
				return map;
			}

		} catch (Exception ex) {
			pool.returnBrokenResource(jedis);
			logger.error("未知错误!", ex.fillInStackTrace());
			
			throw new BusinessException(Constants.ERROR_STATE, Constants.ERROR_TIP);
		} finally {
			returnResource(pool, jedis);
		}
		return Maps.newHashMap();
		// jedis
	}
	
	
	@SuppressWarnings("deprecation")
	public static String getValueByKey(String key){
		Jedis jedis = null;
		Pipeline pipe = null;
		String value = null;
		// Map<String,String> map = Maps.newHashMap();
		try {
			jedis = instance();
			if (null != jedis) {
				 pipe = jedis.pipelined();
				// 获取当前所有的key
				value = jedis.get(key);
				pipe.sync();
			}
           
			// System.out.println("---"+map.size());
		} catch (Exception ex) {
			pool.returnBrokenResource(jedis);
			logger.error("未知错误!", ex.getCause());
			ex.printStackTrace();
		} finally {
			returnResource(pool, jedis);
			closeResource(pipe);
		}
		 return value;
	}
	

	
	
	
	/**
	 * @throws IOException 
	 * 
	 * @Title: deleteKey
	 * @Description: 删除单个key
	 * @param @param key 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	@SuppressWarnings("deprecation")
	public static void deleteKey(final String key) {
		Jedis jedis = null;
		Pipeline pipe = null;
		// Map<String,String> map = Maps.newHashMap();
		try {
			jedis = instance();
			if (null != jedis) {
				 pipe = jedis.pipelined();
				// 获取当前所有的key
				jedis.del(key);
				pipe.sync();
			}

			// System.out.println("---"+map.size());
		} catch (Exception ex) {
			pool.returnBrokenResource(jedis);
			logger.error("未知错误!", ex.getCause());
			ex.printStackTrace();
		} finally {
			returnResource(pool, jedis);
			closeResource(pipe);
		}
	}

	/**
	 * @throws IOException 
	 * 
	 * @Title: deleteKey
	 * @Description: 删除批量key
	 * @param @param key 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	@SuppressWarnings("deprecation")
	public static void deleteBatchKey(final String... key) throws IOException {
		Jedis jedis = null;
		Pipeline pipe = null;
		// Map<String,String> map = Maps.newHashMap();
		try {
			jedis = instance();
			if (null != jedis) {
				pipe = jedis.pipelined();
				// 获取当前所有的key
				jedis.del(key);
				pipe.sync();
			}

			// System.out.println("---"+map.size());
		} catch (Exception ex) {
			pool.returnBrokenResource(jedis);
			logger.error("未知错误!", ex.getCause());
			ex.printStackTrace();
		} finally {
			returnResource(pool, jedis);
			closeResource(pipe);
		}
	}

	
	@SuppressWarnings("deprecation")
	public static Set<String> scanAllKeys(String key) {
		Jedis jedis = null;
		try {
			jedis = instance();
			if (null != jedis) {
				return jedis.hkeys(key);
			}

		} catch (Exception ex) {
			pool.returnBrokenResource(jedis);
			logger.error("未知错误!", ex.getCause());
			ex.printStackTrace();
			throw new BusinessException(Constants.ERROR_STATE, Constants.ERROR_TIP);
		} finally {
			returnResource(pool, jedis);
		}
		return Sets.newHashSet();
		// jedis
	}
	
	public static void main(String[] args) {
//		 Map<String, String> map = Maps.newHashMap();
//		 String key = "陕A2309875黄";
//		 map.put("x", "125.456745");
//		 map.put("y", "183.4567567");
//		 RedisAPI.writeByMultKey(key, field, value);
		//{y=153.40, x=125.450}
		//{y0=153.440, x6=125.436, y1=153.441, x7=125.437, y2=153.442, y3=153.443, x4=125.434, y4=153.444, x5=125.435, x2=125.432, y5=153.445, y6=153.446, x3=125.433, y7=153.447, x0=125.430, y8=153.448, x1=125.431, x9=125.439, x8=125.438, y9=153.449}
		//{y0=153.443450, x6=125.43126, y1=153.443451, x7=125.43127, y2=153.443452, y3=153.443453, x4=125.43124, y4=153.443454, x5=125.43125, x2=125.43122, y5=153.443455, y6=153.443456, x3=125.43123, y7=153.443457, x0=125.43120, y8=153.443458, x1=125.43121, x9=125.43129, x8=125.43128, y9=153.443459}
//		 List<ConsumMomeyLimitVo> list = Lists.newArrayList();
//		 for(int i = 0;i<10000;i++){
//		 Map<String, String> map = Maps.newHashMap();
//		 String key = "500000";
//		 map.put("x"+i, "125.4312"+i);
//		 map.put("y"+i, "153.44345"+i);
//		 list.add(new ConsumMomeyLimitVo(key, map));
//		 }
//		 RedisAPI.writeByMultKeyBatch(list);
//		 System.out.println("----"+RedisAPI.scanByHKey(Constants.FIRST_KEY));
//		 RedisAPI.add("3104800099992924686", "1234567890");
		RedisAPI.add("admin", "222222");
		 System.out.println(RedisAPI.getValueByKey("admin"));
		// System.out.println(RedisAPI.gethkey("陕A2309875黄"));
//		long starttime = System.currentTimeMillis();
//		Set<String> list = RedisAPI.scanKeyByMatch("*黄*");
//		long endtime = System.currentTimeMillis();
//		System.out.println("查询消耗时间:" + (endtime - starttime) + "ms" + "---"
//				+ list.size());
//		// RedisAPI.deleteBatchKey("zhangsna");
//		System.out.println("----------------------"
//				+ RedisAPI.gethkey("陕A2309875黄"));
//
//		List<String> list1 = RedisAPI.getRangeData("*", 0, -1);
//		System.out.println(list1.size());

	}
}
